package cn.bone.demo01;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Created by Administrator on 2018/1/29.
 */
public class TimeClientHandler extends ChannelInboundHandlerAdapter {

    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端消息:连接服务器成功");
        byte[] reps = "我是客户端呢\n".getBytes("UTF-8");
        ByteBuf byteBuf = Unpooled.buffer(reps.length);
        byteBuf.writeBytes(reps);
        ctx.write(byteBuf);
        ctx.flush();
//        ctx.writeAndFlush(byteBuf);
    }

    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        System.out.println("客户端消息:断开与服务器的连接");
    }

    /**
     * 读取数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf)msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req,"UTF-8");
        System.out.println("客户端接口服务端消息:"+body);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        System.out.println("出现异常:"+cause.getMessage());
        ctx.close();
    }
}
